<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Carousel;
use App\Models\Mp;
use App\Services\BaiduSearchService;
use App\Services\LotService;
use App\Services\UtilsService;
use App\Services\WebsocketDataService;
use App\Services\WuKongImService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\Crawler\Crawler;

class PublicController extends Controller
{
    public function test(Request $request)
    {
        $query = $request->input('query', 'songshu.youyacao.com');
        $page = $request->input('page', 1);
        $results=new BaiduSearchService();
        $ss=$results->search($query,$page);
//        return $ss;
        dd($ss);
        $getProjectTop = (new WebsocketDataService())->getProjectTop();
        dd($getProjectTop);
        $this->send($request);
        exit;
        $num = rand(1, 100);
        return $this->success('success', $num);
//       $dev=new LotService();
////       $list=$dev->DeviceByStatusList($request);
////       $list=$dev->getQueryDevice($request);
//       $list=$dev->Pub($request->status,$request->name);
//       return $this->success('success',$list);
    }

    public function publicNotice()
    {
        return $this->success('success',[config("publicNotice.key")]);
    }

    public function carousel(Request $request)
    {
        if (!$request->has('mp') || !is_numeric($request->mp) || !in_array($request->mp, Mp::pluck('id')->toArray())) {
            return $this->error('小程序码配置错误');
        }
        $list=Carousel::where('status',1)
            ->where('mps_id', $request->mp)
            ->select('id', 'name', 'url', 'sort', 'goto', 'episodes_id')
            ->orderByDesc('sort')
            ->get()
            ->toArray();
        if (empty($list)) {
            return $this->error('数据为空');
        }
        return $this->success('success', $list);
    }

    public function uploadImage(Request $request)
    {
        // 获取base64图片数据
        $imageData = $request->input('image');
        $imageDataParts = explode(',', $imageData);
        $imageFormat = '';

        if (count($imageDataParts) > 1) {
            $imageFormatPart = explode(';', $imageDataParts[0]);
            if (count($imageFormatPart) > 0) {
                $imageFormat = explode('/', $imageFormatPart[0])[1];
            }
        }
        if (!in_array($imageFormat, ['png', 'jpg', 'jpeg'])) {
            return $this->error('格式错误');
        }
        $decodedImage = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $imageData));

        // 生成一个唯一的文件名
        $fileName = uniqid() . '.' . $imageFormat;

        // 保存图片到存储系统（例如，本地存储或云存储）
        Storage::disk('admin')->put($fileName, $decodedImage);
        // 获取图片的完整URL
        $imageUrl = asset('uploads/' . $fileName);
        // 返回图片的URL
        return $this->success('success', ['image_url' => $imageUrl]);
    }



public function uploadImage2(Request $request)
{
    // 初始化变量
    $imageData = null;
    $imageFormat = '';
    $fileName = '';
    $imageUrl = '';

    // 检查是否有直接上传的文件
    if ($request->hasFile('image')) {
        // 文件上传处理
        $file = $request->file('image');
        if (!$file->isValid()) {
            return $this->error('文件上传出错');
        }

        // 获取文件扩展名
        $extension = $file->getClientOriginalExtension();
        if (!in_array(strtolower($extension), ['png', 'jpg', 'jpeg'])) {
            return $this->error('只支持png, jpg, jpeg格式');
        }

        // 生成一个唯一的文件名并保留原始扩展名
        $fileName = Str::random(40) . '.' . $extension;

        // 保存文件到指定磁盘
        Storage::disk('admin')->put($fileName, file_get_contents($file));

    } elseif ($request->input('image')) {
        // Base64图片数据处理
        $imageData = $request->input('image');
        $imageDataParts = explode(',', $imageData);

        if (count($imageDataParts) > 1) {
            $imageFormatPart = explode(';', $imageDataParts[0]);
            if (count($imageFormatPart) > 0) {
                $imageFormat = explode('/', $imageFormatPart[0])[1];
            }
        }

        if (!$imageFormat || !in_array(strtolower($imageFormat), ['png', 'jpg', 'jpeg'])) {
            return $this->error('格式错误或未找到Base64图片数据');
        }

        // 解码并准备保存
        $decodedImage = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $imageData));

        // 生成文件名
        $fileName = Str::random(40) . '.' . strtolower($imageFormat);
        Storage::disk('admin')->put($fileName, $decodedImage);
    } else {
        return $this->error('请提供Base64图片数据或直接上传文件');
    }

    // 构建图片URL
    $imageUrl = Storage::disk('admin')->url($fileName);

    // 返回成功响应及图片URL
    return $this->success('上传成功', ['image_url' => $imageUrl]);
}


    public function send(Request $request)
    {
        $wukongservice = new WuKongImService();
        $uid = 'admin';
        $wukongservice->reg($uid, 'fdskfkj');
        return $wukongservice->sendTo($uid, $request->formuid, $request->message);

    }

    public function ipchaxun(Request $request)
    {
        $utils=new UtilsService();
        $data=$utils->ipTo($request->input('ip'));
        return $this->success('success',$data);
    }

    public function httpbaidu()
    {

    }

    public function test2(Request $request)
    {
        $chache=Cache::get('test2');
        if($chache){
            return $this->success('success',$chache);
        }else{
            Cache::put('test2', 'test2', 30);
            $chache=Cache::get('test2');
            return $this->success('success2',$chache);
        }

    }
}
